<template>
	<view class="container" v-if="loading">
		<tui-navigation-bar @init="initNavigation" :transparent="true" backgroundColor="#313431" color="#222222">
			<view class="tui-header" :style="{ marginTop: navBarTop + 'px' }">
				<view class="get-back dy-iconfont icon-qiehuanqizuo" @click="goBack()">
				</view>
			</view>
		</tui-navigation-bar>
		<view class="main">
			<view class="title" v-if="redEnvelope == 1">尊享体验</view>
			<view class="title" v-else>恭喜您已成功获得权益</view>
			<!-- <view class="title2">恭喜您已成功购买礼包膨胀红包拼手气，爆红包哇塞，成功爆涨您有一份0元购权益待查收</view> -->
			<view class="advertising-1" :class="{'advertising-3': redEnvelope != 1}" @tap.stop.prevent="upgrade"></view>
			<view class="advertising-2" v-if="redEnvelope == 1"></view>
			<button class="advertising-2" v-else @tap.stop.prevent="share" open-type="contact"></button>
			<view class="rule">
				<view class="rule-title">使用规则</view>
				<view class="con">1.用户支付1元（好评后可返）可获得一张10元无门槛抵用券</view>
				<view class="con">2.分享小程序给3个好友并邀请对方注册成功后，您将获得一次优惠翻倍的机会，最高可暴涨至30元</view>
				<view class="con">3.限量1万份，每个ID限购一次</view>
				<view class="con">4.已经购买成功的用户，如因某些特殊原因需要取消订单的，可联系客服人员协助取消订单，退款后不可再次购买</view>
				<view class="con">5.订单完成并好评后，可以联系客服返1元</view>
			</view>
			<view class="notice-bar">
				<uv-notice-bar :customStyle="customStyle" :text="text" direction="column" bgColor="#808080"
					color="#FFFFFF" fontSize="20rpx"
					icon="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/avatar/2023/12/07/7a77234babf84a85bd18febab4f6f401.png"></uv-notice-bar>
			</view>
			<view class="payment-btn-box">
				<view class="payment-btn" @tap.stop.prevent="payment" v-if="redEnvelope == 1"></view>
				<view class="payment-sucss-btn" @tap.stop.prevent="lookRedEnvelope" v-else-if="redEnvelope == 2"></view>
				<view class="payment-my" v-else @tap.stop.prevent="goMycoupon"></view>
				<view class="payment-animation"></view>
				<view class="ttt" v-if="redEnvelope == 1">好评后返回</view>
			</view>
		</view>
		<expansion ref="expansion" @expansionRedEnvelopePopupchange="expansionRedEnvelopePopupchange"
			:defaultStep="defaultStep" :inviteList="couponDetail.inflationList" :show="redEnvelopeShow"
			:userCouponId="couponDetail.userCouponId"></expansion>
		<uv-toast ref="toast"></uv-toast>
		<survey-pop></survey-pop>
	</view>
</template>

<script>
	import mp from "@/mixins/mp.js";
	import tabbar from '@/components/custom-tabbar/custom-tabbar.vue';
	import expansion from '@/components/expansion-red-envelope/view.vue';
	import throttle from '@/uni_modules/uv-ui-tools/libs/function/throttle.js';
	const app = getApp();

	export default {
		mixins: [mp],
		components: {
			tabbar,
			expansion
		},
		data() {
			return {
				navBarTop: 0, // 导航栏content顶部m-top
				text: ['浙江省尾号2345的用户购买成功'],
				customStyle: {
					width: '358rpx',
					height: '52rpx',
					borderRadius: '12rpx',
					justifyContent: 'center',
					boxSizing: 'border-box',
					padding: '0 16rpx'
				},
				isBuy: 0,
				couponDetail: {
					inflationList: [],
					userCouponId: null
				},
				loading: false,
				UserInfo: {},
				redEnvelope: 1,
				defaultStep: 1,
				redEnvelopeShow: false,
			};
		},
		/**
		 * 计算属性
		 */
		computed: {},
		onLoad(options) {
			this.isBuy = options.isBuy
		},
		onShow: function() {
			this.userInfo = uni.getStorageSync('user_info') ? uni.getStorageSync('user_info') : null;
			if (this.userInfo) {
				this.getCouponDetail()
			} else {
				this.loading = true
			}
			this.getNoticeText(10)
		},
		onShareAppMessage: function() {
			//转发参数
			return {
				// 转发的标题
				title: 'PENG一下，趣收获',
				desc: 'PENG一下，趣收获',
				// 转发的路径，默认是当前页面，必须是以‘/’开头的完整路径，/pages/index/index
				path: '/pages/index/index?invite_code=' + this.userInfo.authInfo.userId,
				//自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，
				//支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
				// imageUrl: 'https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/share/share-1.png',
			}
		},
		/**
		 * 下拉
		 */
		onPullDownRefresh: function() {},
		/**
		 * 触底
		 */
		onReachBottom() {},
		/**
		 * 滚动
		 */
		onPageScroll(e) {},
		methods: {
			initNavigation(e) {
				this.navBarTop = e.top;
			},
			goLogin() {
				app.doLogin()
			},
			// 0元购支付 --------------------------------------

			getCoupon() {
				return new Promise((resolve, reject) => {
					app._get(
						"/client/coupon/query/coupon-toast", null,
						(result) => {
							let res = result.data
							resolve(res);
						}, null, () => {
							resolve(false);
						}
					);
				});
			},

			async getCouponDetail() {
				let that = this
				const res = await that.getCoupon()
				return new Promise((resolve, reject) => {
					app._post_form(
						"/client/coupon/query/coupon-detail", res.couponId,
						(result) => {
							let data = result.data
							uni.setStorageSync('coupon_detail', result.data);
							app.globalData.couponDetail = result.data
							that.couponDetail = result.data
							that.redEnvelope = data.userCouponId ? data.couponStatus == 1 ? data
								.inflationState == 1 ? 3 : 2 : 3 : 1
							that.defaultStep = data.userCouponId ? data.couponStatus == 1 ? data
								.inflationState == 1 ? 10 : 2 : 10 : 1
							setTimeout(() => {
								if (!that.redEnvelopeShow && that.redEnvelope == 2) {
									that.redEnvelopeShow = true
								}
							}, 500)
							resolve(result);
						}, null, () => {
							that.loading = true
						}
					);
				});
			},
			payState(id) {
				let that = this
				return new Promise((resolve, reject) => {
					app._post_form(
						"/client/order/query/pay-state", id,
						(result) => {
							that.$refs.toast.hide()
							console.log('支付结果', result);
							if (result.data.payState != 0) {
								that._clearCount()
								this.getCouponDetail()
								this.defaultStep = 1
								this.redEnvelopeShow = true
							}
							resolve(result);
						}, () => {
							that.$refs.toast.hide()
							that._clearCount()
						}, null, () => {
							that.$refs.toast.hide()
							that._clearCount()
						}
					);
				});
			},
			_codeCount(id) {
				let that = this
				that.$refs.toast.show({
					type: 'loading',
				})

				that.codeTimer = setInterval(() => {
					if (that.codeTime <= 0) {
						clearInterval(that.codeTimer);
						that.codeTimer = null;
						that.codeTime = 0;
						that.$refs.toast.hide()
						/* 清除定时的逻辑*/
					} else {
						/*未请求到接口，继续请求数据*/
						that.payState(id)
						that.codeTime--;
					}
				}, 2000);
			},
			//清除定时器
			_clearCount() {
				clearInterval(this.codeTimer);
				this.codeTimer = null;
				this.codeTime = 0;
			},

			saveReserve(params) {
				return new Promise((resolve, reject) => {
					app._post_form(
						"/client/coupon/submit/coupon-order", params,
						(result) => {
							resolve(result);
						}, null, () => {
							reject();
						}
					);
				});
			},
			lookOver(buy) {
				uni.navigateTo({
					url: '/page_account/advertising/advertising?isBuy=' + buy
				})
			},
			goMycoupon() {
				uni.navigateTo({
					url: '/page_user/discount/discount'
				})
			},
			payment() {
				let that = this
				if (!that.userInfo) {
					app.doLogin()
					return
				}
				if (that.isBuy == 1) {
					that.lookOver(1)
					return
				}
				that.$refs.toast.show({
					type: 'loading',
				})
				let provider = uni.getProvider({
					service: 'payment'
				})
				that.saveReserve(that.couponDetail.couponId).then(res => {
					that.$refs.toast.hide()
					let data = res.data
					// res为调起微信支付所需参数
					// 调起微信支付
					uni.requestPayment({
						provider: 'wxpay', // 服务提提供商
						appId: data.appId,
						timeStamp: data.timeStamp, // 时间戳
						nonceStr: data.nonceStr, // 随机字符串
						package: data.prepayId,
						signType: data.signType, // 签名算法
						paySign: data.paySign, // 签名
						success: function(res) {
							console.log('支付成功', res);
							// 业务逻辑。。。
							that._codeCount(data.orderId)
						},
						fail: function(err) {
							console.log('支付失败', err);
						}
					});
				}).catch(err => {
					that.$refs.toast.hide()
					console.log(err);
				})
			},

			//  ------------------------------------------------------------
			share() {},

			upgrade() {
				if (this.redEnvelope != 1) {
					this.lookRedEnvelope()
				}
			},
			lookRedEnvelope() {
				let that = this
				that.$refs.toast.show({
					type: 'loading',
				})

				this.getCouponDetail().then(res => {
					that.$refs.toast.hide()
					throttle(this.showEnvelopePop(), 1000)
				})
			},
			showEnvelopePop() {
				this.defaultStep = 2
				this.redEnvelopeShow = true
			},
			expansionRedEnvelopePopupchange() {
				this.redEnvelopeShow = false
			},
			//随机数
			getRnd(min, max) {
				return Math.floor(Math.random() * 10000)
			},
			//随机城市
			getCity(min, max) {
				var cityList = ['北京市', '上海市', '江苏省', '浙江省', '福建省', '广东省', '四川省'];
				return cityList[Math.floor(Math.random() * cityList.length)]
			},
			getNoticeText(num) {
				for (var i = 0; i < num; i++) {
					let noticeText = this.getCity() + '尾号' + this.getRnd() + '的用户购买成功'
					this.text.push(noticeText)
				}

			},
			// 返回上一页
			goBack: function() {
				app.beNavigateBack();
				// app.navigationTo('pages/index/index');
			},
		},
	};
</script>
<style lang="scss" scoped>
	.container {
		position: relative;
		padding-top: 412rpx;
		box-sizing: border-box;
		min-height: 100vh;
		z-index: 1;

		&::after {
			position: absolute;
			display: block;
			left: 0;
			right: 0;
			top: 0;
			content: '';
			width: 100%;
			height: 450rpx;
			background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/free-purchase/free-purchase-bg.png');
			background-repeat: no-repeat;
			background-size: cover;
			z-index: -2;
		}

		.tui-header {
			width: 100%;
			position: fixed;
			top: 0;
			padding: 0 42rpx;
			display: flex;
			align-items: center;
			height: 32px;
			transform: translateZ(0);
			z-index: 99999;
			box-sizing: border-box;

			.get-back {
				flex-shrink: 0;
				width: 36rpx;
				height: 36rpx;
				color: #000;
				font-size: 36rpx;
				padding: 2rpx 40rpx 2rpx 2rpx;
			}
		}

		.main {
			box-sizing: border-box;
			padding: 36rpx 24rpx;
			background: #FFFFFF;
			width: 100vw;
			height: calc(100vh - 412rpx);
			border-radius: 40rpx 40rpx 0rpx 0rpx;

			.title {
				font-weight: 900;
				font-size: 32rpx;
				line-height: 45rpx;
				background-image: linear-gradient(90deg, #B16911 0%, #E9920C 100%);
				-webkit-background-clip: text;
				-webkit-text-fill-color: transparent;
				vertical-align: middle;
				text-align: center;
				margin-bottom: 24rpx;

				&::before {
					display: inline-block;
					content: '';
					width: 64rpx;
					height: 64rpx;
					background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/free-purchase/icon.png');
					background-repeat: no-repeat;
					background-size: cover;
					margin-right: 9rpx;
					vertical-align: middle;
				}
			}

			.advertising-1 {
				width: 702rpx;
				height: 180rpx;
				border-radius: 40rpx;
				background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/free-purchase/free-list-1.png');
				background-repeat: no-repeat;
				background-size: cover;
				box-sizing: border-box;
				margin-bottom: 17rpx;
			}

			.advertising-3 {
				background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/free-purchase/free-list-3.png');
			}

			.advertising-2 {
				width: 702rpx;
				height: 180rpx;
				border-radius: 40rpx;
				background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/free-purchase/free-list-2.png');
				background-repeat: no-repeat;
				background-size: cover;
				margin: 0;
				margin-bottom: 60rpx;
				padding: 0;
			}

			.rule {
				margin-bottom: 82rpx;
				box-sizing: border-box;
				padding: 0 12rpx;

				.rule-title {
					font-weight: 900;
					font-size: 32rpx;
					color: #1E1F1F;
					line-height: 45rpx;
					margin-bottom: 24rpx;
				}

				.con {
					font-weight: 400;
					font-size: 24rpx;
					color: #999B9B;
					line-height: 33rpx;
				}
			}

			.notice-bar {
				margin-bottom: 32rpx;
			}

			.payment-btn-box {
				position: relative;
				width: 636rpx;
				height: 142rpx;
				margin: 0 auto;
				border-radius: 40rpx;

				.payment-animation {
					width: 107rpx;
					height: 102rpx;
					background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/free-purchase/animation-3.png');
					background-repeat: no-repeat;
					background-size: cover;
					position: absolute;
					top: 8rpx;
					left: 22rpx;
					animation: slide-in-left 0.9s ease 0s infinite;
				}

				.ttt {
					position: absolute;
					top: -16rpx;
					right: 0;
					width: 158rpx;
					height: 52rpx;
					background: #FFF2D0;
					border-radius: 30rpx;
					font-weight: 600;
					font-size: 24rpx;
					color: #FF4E04;
					line-height: 52rpx;
					text-align: center;
				}
			}

			.payment-btn {
				width: 636rpx;
				height: 142rpx;
				border-radius: 40rpx;
				background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/free-purchase/payment-btn.png');
				background-repeat: no-repeat;
				background-size: cover;
			}

			.payment-sucss-btn {
				width: 636rpx;
				height: 142rpx;
				border-radius: 40rpx;
				background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/free-purchase/payment-btn-suc.png');
				background-repeat: no-repeat;
				background-size: cover;
			}

			.payment-my {
				width: 636rpx;
				height: 142rpx;
				border-radius: 40rpx;
				background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/free-purchase/payment-btn-my.png');
				background-repeat: no-repeat;
				background-size: cover;
			}
		}
	}

	@keyframes slide-in-left {
		0% {
			left: 22rpx;
			opacity: 1;
		}

		90% {
			left: 479rpx;
			opacity: 0;
		}

		100% {
			left: 22rpx;
			opacity: 0;
		}
	}
</style>